package Controller;

import Dto.NewsTbEntity;
import MEx.MExAPI;
import repository.FindNewsRepository;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;


@WebServlet(name = "FindNews_head")
public class FindNews_head extends HttpServlet{
    private static final long serialVersionUID = 1L;


    public FindNews_head(){
        super();
        //TODO Auto-generated constructor stub
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
        response.setContentType("text/html;charset=UTF-8");
        String Headline = new String(request.getParameter("Headline").getBytes("ISO8859-1"),"UTF-8");
        System.out.println("Headline="+Headline);

        PrintWriter out = response.getWriter();

        try {
            FindNewsRepository findNewsRepository = new FindNewsRepository();
            NewsTbEntity newsTbEntity = new NewsTbEntity();
            boolean resssss = false;
            resssss = findNewsRepository.FindNews_Head(Headline,newsTbEntity);
            System.out.println("resssss="+resssss);

            if (findNewsRepository.FindNews_Head(Headline,newsTbEntity)){


                System.out.println("head="+newsTbEntity.getNewsHeadline());

                String JsonStr = "{\"NewsContents\":";

                String[] keys = {"Headline","Name","Content","UpTime"};
                Object[] objs = {newsTbEntity.getNewsHeadline(),newsTbEntity.getNewsName(),newsTbEntity.getNewsContent(),newsTbEntity.getUpTime()};
                JsonStr += MExAPI.toJson(keys,objs);
                JsonStr += ",";
                out.write(JsonStr +"\"Result\":\"Success\"}");
            }
            else {
                out.write("{\"Result\":\"Fail\"}");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.write("{\"Result\":\"Fail\"}");
        }
        finally{
            out.flush();
            out.close();
        }
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}